/**
 * Created by zhanshen886 on 2019/1/21.
 */
/**
 * Created by zhanshen886 on 2019/1/18.
 */
function Animator(duration, progress) {
    this.duration = duration;
    this.progress = progress;
    this.next = true;
}
Animator.prototype = {
    constructor: Animator,
    start: function (finished) {
        var startTime = new Date().getTime();
        var duration = this.duration, self = this, timeOut = 0;
        var vendors = ["webkit", "moz"];
        for (var i = 0; i < vendors.length && !window.requestAnimationFrame; ++i) {
            window.requestAnimationFrame = window[vendors[i] + "RequestAnimationFrame"];
        }
        if (!window.requestAnimationFrame) {
            window.requestAnimationFrame = function (callback, element) {
                var start = 0, finish = 0;
                window.setTimeout(function () {
                    start = +new Date();
                    callback(start);
                    finish = +new Date();
                    timeOut = 1000 / 300 - (finish - start);
                }, timeOut);
            };
        }
        window.requestAnimationFrame(function step() {
            var p = (new Date().getTime() - startTime) / duration;
            //var y = p * p * p;
            self.progress(p, p);
            if (p >= 1.0) {
                self.progress(1.0, 1.0);
                self.next = false;
                finished();
            }
            if (self.next) window.requestAnimationFrame(step);
        });
    },
    stop: function () {
        this.next = false;
    }
};
var code = Epg.getParam("code", "ggly_iptv_animation");
CONFIG.COLUMN_CODE = code;
var uri = "column/secondPage/secondPage" + CONFIG.EXT + "?1=1&code=" + code;
var SecondPage = {
    //userid: Epg.cookie.get("userid"),
   // role: Epg.cookie.get("role"),
   // orderType: Epg.cookie.get("orderType"),
    side_idx: Epg.getParamInt("side_idx", "0"),							// 侧边栏菜单项隐藏了多少个
    sidePrevButtonId: Epg.getParam("sidePrevButtonId", "side_0"),		// 侧边栏离开时的id
    navPrevButtonId: Epg.getParam("navPrevButtonId", ""),				// 菜单离开时的id
    recommendPrevButtonId: Epg.getParam("recommendPrevButtonId", ""),	// 推荐位离开时的id
    carousel_index: Epg.getParamInt("carousel_index", 1),				// 大推荐位滚屏到第几屏了

    sideClick: function () {												// 侧边栏点击事件
        if (SecondPage.sidePrevButtonId === Epg.btn.current.id) return;
        SecondPage.sidePrevButtonId = Epg.btn.current.id;
        //SecondPage.updateSideBg();										// 更新侧边栏菜单项背景图
        SecondPage.init();												// 初始化推荐位信息
    },
    sideBeforeMove: function (dir, current) {							// 侧边栏移动前判断事件
        if ("right" === dir) {
            //SecondPage.sidePrevButtonId = current.id;
            if (SecondPage.recommendPrevButtonId !== "") {
                Epg.btn.set(SecondPage.recommendPrevButtonId);
            } else if (Epg.btn.get("label_recommend_0")) {
                Epg.btn.set("label_recommend_0");
            } else {
                Epg.btn.set("recommend_big");
            }
            return false;
        } else if ("up" === dir && !(current.up && current.up.length > 0)) {
            Epg.btn.set(SecondPage.navPrevButtonId || 'nav_' + navs2[code][0]);
            return false;
        }
    },
    sideFocusHandler: function (current) {								// 侧边栏菜单项获得焦点
        var index = current.index;
        if (index < SecondPage.side_idx) {
            SecondPage.side_idx = SecondPage.side_idx - (SecondPage.side_idx - index);
            G("sides").scrollTop = 46 * SecondPage.side_idx;			// 向上移动46个像素
        } else if (index > (SecondPage.side_idx + (3 + navs2[code][1] * 2))) {
            SecondPage.side_idx = SecondPage.side_idx + (index - SecondPage.side_idx - (3 + navs2[code][1] * 2));
            G("sides").scrollTop = 46 * SecondPage.side_idx;			// 向下移动46个像素
        }
        G("side_more").style.visibility = (SecondPage.side_idx + 3 + navs2[code][1] * 2) < groups[1].metadatas.length ? 'visible' : 'hidden';
    },
    updateSideBg: function () {											// 更新侧边栏菜单项背景颜色
        var side = parseInt((SecondPage.sidePrevButtonId).slice(5));
        var span = document.querySelector("#sides").getElementsByTagName("span");
        Array.prototype.slice.call(span).forEach(function (value, index) {
            if (index === side) {
                Epg.addClass(value, "side_focus");
                value.getElementsByTagName("div")[0].style.color = "#944600";
                value.getElementsByTagName("div")[0].style.fontWeight = "900";
            } else {
                Epg.removeClass(value, "side_focus");
                value.getElementsByTagName("div")[0].style.color = "#FFFFFF";
                value.getElementsByTagName("div")[0].style.fontWeight = "400";
            }
        });
        G("recommend_down").style.visibility = side === groups[1].metadatas.length ? "hidden" : "visible";
    },
    initSide: function (flag, f) {										// 初始化侧边栏
        var val = code.slice(10);							// 截取二级页面关键字作为侧边栏菜单项背景取色
        SecondPage.initButtons();							// 初始化buttons数组
        var metadatas = groups[1].metadatas;				// 获取配置内容第二个数组
        var html = '<div class="sides">';
        var str = [];										// 把侧边栏菜单项值组装在一起，查询点播前5位的视频信息
        html += '<span class="' + val + '"><div id="side_0" class="side_txt">精选推荐</div></span>';
        for (var i = 0, length = metadatas.length; i < length; i++) {
            str.push("'" + metadatas[i].value + "'");
            html += '<span class="' + val + '"><div id="side_' + (i + 1) + '" class="side_txt">' + metadatas[i].label + '</div></span>';
        }
        if ("true" === flag) {
            SecondPage.initDjdak(str.join(","), f);
        }
        html += '</div>';
        G("sides").innerHTML = html;
        G("sides").scrollTop = 46 * SecondPage.side_idx;
        G("side_more").style.visibility = (SecondPage.side_idx + 3 + navs2[code][1] * 2) < length ? 'visible' : 'hidden';	// 更多侧边栏菜单项箭头是否显示
        SecondPage.updateSideBg();
    },
    recommendClick: function () {										// 推荐位点击事件
        SecondPage.updateCurrentUri();
        var id = Epg.btn.current.id;
        var code=Epg.btn.current.code;
        console.log("code:::"+code);
        location.href = './shop_detail.html?id=' + code;
    },
    isOrder: function (recommend) {										// 推荐位等的判断事件
        var type = recommend.type, code = recommend.code;
        if ('album' === type || 'activity' === type) {
            SecondPage.getActivityOrAlbum(code);
        } else if ('recommend_series' === type) {
            Epg.go('column/subSeries/subSeries' + CONFIG.EXT + '?code=' + code);
        } else {
            if ("free" != SecondPage.orderType) {
                Epg.goMP('column/mp/mp' + CONFIG.EXT + '?method=playVideo&code=' + code);
            } else {
                Epg.go('column/order/order' + CONFIG.EXT + '?source=' + CONFIG.COLUMN_CODE + '&code=' + code);
            }
        }
    },
    getActivityOrAlbum: function (code) {								// 进入活动或者专辑页面
        var postData = {'code': code, 'appVersion': CONFIG.APP_VERSION, 'role': SecondPage.role};
        Epg.postAPI('epg/get', postData, function (data) {
            if (data && data.code === 0) {
                Epg.go(data.epg.path);
            }
        });
    },
    recommendBeforeMove: function (dir, current) {						// 推荐位移动前的判断事件
        if ("left" === dir && !(current.left && current.left.length > 0)) {
            SecondPage.recommendPrevButtonId = current.id;
            Epg.btn.set(SecondPage.sidePrevButtonId);
            return false;
        } else if ("up" === dir && !(current.up && current.up.length > 0)) {
            SecondPage.recommendPrevButtonId = current.id;
            Epg.btn.set(Home.ipPrevButtonId || 'tj_type_state_1');
            return false;
        }
    },
    recommendFocusHandler: function () {
        Epg.marquee.start();
        var id = Epg.btn.current.id;
        Epg.addClass(G(id).parentElement, 'label_recommend_scale');
    },
    recommendBlurHandler: function () {
        Epg.marquee.stop();
        var id = Epg.btn.previous.id;
        Epg.removeClass(G(id).parentElement, 'label_recommend_scale');
    },
    marqueeStart: function () {											// 文本进行滚动
        var id = Epg.btn.current.id + '_txt';
        var marqueeParent = G(id);
        var html = Epg.trim(marqueeParent.innerHTML);
        SecondPage.html = html;
        marqueeParent.innerHTML = '<div id="' + id + '_marquee" class="marquee"><div><div>' + html + '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</div><div>' + html + '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</div></div></div>';
        var marqueeChild = G(id + '_marquee').getElementsByTagName('div')[0].getElementsByTagName('div')[0];
        var width1 = parseInt(Epg.css(marqueeParent, 'width'));
        var width2 = parseInt(Epg.css(marqueeChild, 'width'));
        if (width1 < width2) {
            //var offsetWidth = marqueeChild.getElementsByTagName('div')[0].offsetWidth;
            function scroll() {
                animator = new Animator(6000, function (p) {
                    if (G(id + '_marquee')) {
                        G(id + '_marquee').scrollLeft = p * width2;
                    }
                });
                animator.start(function () {
                    G(id + '_marquee').scrollLeft = 0;
                    scroll();
                })
            }

            scroll();
        } else {
            G(id).innerHTML = '<div id="' + id + '_marquee" class="marquee"><div><div>' + html + '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</div></div></div>';
        }
    },
    marqueeStop: function () {											// 文本滚动停止
        var id = Epg.btn.previous.id + '_txt';
        animator && animator.stop();
        G(id + '_marquee').scrollLeft = 0;
        G(id).innerHTML = SecondPage.html;
    },
    djdakFocusHandler: function (current) {								// 大家都爱看文本获得焦点
        var id = current.id;
        var name = current.videoName;
        if ("ggly_iptv_song" === CONFIG.COLUMN_CODE) {
            name = current.seriesName;
        }
        G(id + "_txt").innerHTML = name;
        SecondPage.marqueeStart();
    },
    djdakBlurHandler: function (prev) {									// 大家都爱看文本失去焦点
        var id = prev.id;
        SecondPage.marqueeStop();
        var name = prev.seriesName;
        if ("ggly_iptv_song" === CONFIG.COLUMN_CODE) {
            name = prev.videoName;
        }
        G(id + "_txt").innerHTML = name;
    },
    initDjdak: function (label, f) {										// 初始化大家都爱看列表信息
        document.querySelector('.djdak_title').style.backgroundImage = 'url(images/djdak_title.png)';
        document.querySelector(".djdak").style.backgroundImage = 'url(images/djdak_bg.png)';
        Epg.postAPI("tag/get-videoList-byTagType", {"tagCode": label, "topLimit": 5}, function (res) {
            if (res && res.code === 0) {
                var videoList = res.videoList, html = "";
                if ("ggly_iptv_song" === CONFIG.COLUMN_CODE) {
                    for (var i = 0, length = videoList.length; i < length; i++) {
                        html += '<div id="djdak_' + i + '"><div id="djdak_' + i + '_txt" class="djdak_txt">' + videoList[i].name + '</div></div>';
                        buttons.push({
                            id: 'djdak_' + i,
                            code: videoList[i].code,
                            videoName: videoList[i].name,
                            seriesName: videoList[i].intro,
                            action: SecondPage.recommendClick,
                            focusHandler: SecondPage.djdakFocusHandler,
                            blurHandler: SecondPage.djdakBlurHandler,
                            beforeMove: SecondPage.recommendBeforeMove,
                            focusClass: 'djdak',
                            autoDirGroup: 4
                        });
                    }
                } else {
                    for (var i = 0, length = videoList.length; i < length; i++) {
                        html += '<div id="djdak_' + i + '"><div id="djdak_' + i + '_txt" class="djdak_txt">' + videoList[i].intro + '</div></div>';
                        buttons.push({
                            id: 'djdak_' + i,
                            code: videoList[i].code,
                            videoName: videoList[i].name,
                            seriesName: videoList[i].intro,
                            action: SecondPage.recommendClick,
                            focusHandler: SecondPage.djdakFocusHandler,
                            blurHandler: SecondPage.djdakBlurHandler,
                            beforeMove: SecondPage.recommendBeforeMove,
                            focusClass: 'djdak',
                            autoDirGroup: 4
                        });
                    }
                }
                G("djdak").innerHTML = html;
            }
            Epg.autoMakeBtnDir(buttons);
            Epg.btn.init([f, 'recommend_big'], buttons, '', false);
        });
    },
    autoPlay: function () {												// 最大推荐位进行轮播
        SecondPage.carousel_index++;
        SecondPage.carousel_index = SecondPage.carousel_index >= 3 ? 0 : SecondPage.carousel_index;
        var span = G("tj_id1").getElementsByTagName('span');
        var li = G("tj_id1").getElementsByTagName('li');
        Array.prototype.slice.call(span).forEach(function (value, index) {
            value.className = index === SecondPage.carousel_index ? 'recommend_big_show' : '';
        });
        Array.prototype.slice.call(li).forEach(function (value, index) {
            value.className = index === SecondPage.carousel_index ? 'recommend_dian' : '';
        });
    },
    initRecommendBig: function () {										// 初始化大推荐位信息
        //var html = "";
        //
        //html += '</ul>';
        //G("recommend_big").innerHTML = html;
        recommend_big_interval = setInterval(function () {
            SecondPage.autoPlay();
        }, 4000);
    },
    initRecommend: function (ID) {											// 初始化分类信息
        $.post(CONFIG.BASEURL+"noLogin/internetTv_getTypeList.msp", {
            isTest: "isTest",
            uuid:"123"
        }, function (data) {
            console.log( data.retdata);
            var retcode = data.retcode;
            if (retcode == 0) {
                var retdata = data.retdata;

            var html=" <div class=\"tj_type\">";

                for (var i = 0; i < retdata.length; i++) {

                    html+=" <div class=\"tj_type_1\" id=\"tj_type_id_"+retdata[i].ID+"\"> "+retdata[i].TYPE_NAME+"</div>";
                    var obj = {
                        id: 'tj_type_id_' + retdata[i].ID,
                        action: Home.ipClick,
                        focusHandler: Home.ipFocusHandler,
                        blurHandler: Home.ipBlurHandler,
                        beforeMove: Home.recommendBeforeMoveHandler,
                        up: [],
                        down: [],
                        focusClass: 'tj',
                        autoDirGroup: 4,
                        scrollDir: 'x'
                    };
                    if (i === 0) {
                        obj['left'] = ['ip_first'];
                        obj['restoreScroll'] = true;
                    } else {
                        obj['scrollScreen'] = true;
                    }
                    buttons.push(obj);
                }
                html+="</div>";
                G("ips").innerHTML = html;
                SecondPage.initLabelRecommend(ID);


            }
        }, "json")
    },
    initLabelRecommend: function (ID) {									// 分类下商品列表接口
        recommend_big_interval && clearInterval(recommend_big_interval);
        var id = Epg.btn.current && Epg.btn.current.id;

        $.post(CONFIG.BASEURL+"noLogin/internetTv_getListByType.msp", {
            id: ID,
            sort:sort,
            isTest:"wondertek",
            uuid:"123"
        }, function (data) {
            console.log( data.retdata);
            var retcode = data.retcode;
            if (retcode == 0) {
                var retdata = data.retdata;

                   var html = '<div class="label_recommends">';
                for (var i = 0, length = retdata.length; i < length; i++) {
                    html += "<div >" +
                        "<div id=\"label_recommend_" + i + "\"></div>" +
                        "<div class=\"div_img\" data-url=\""+retdata[i].SMALL_IMAGE_URL+"\" data-epg-btn></div> <div id=\"label_recommend_" + i + "_txt\" class=\"label_recommend_txt\">"+retdata[i].ELEC_COUPON_NAME+"</div>   <div class=\"tag_score\">  <div class=\"money_txt1\">¥"+retdata[i].PAY_AMOUNT/100+"</div>   " +
                        " <div class=\"money_txt2\">¥"+retdata[i].PRICE/100+"</div>  </div></div> ";

                    var obj = {
                        id: 'label_recommend_' + i,
                        code: retdata[i].ID,
                        right: i >= (length - 1) ? [] : '',
                        up: i < 5 ? [] : '',
                        down: ((Math.ceil((i + 1) / 5) * 5) >= length) ? ['recommend_down'] : '',
                        action: SecondPage.recommendClick,
                        focusHandler: SecondPage.recommendFocusHandler,
                        blurHandler: SecondPage.recommendBlurHandler,
                        beforeMove: SecondPage.recommendBeforeMove,
                        focusClass: 'label_recommend',
                        autoDirGroup: 6
                    };
                    if (i < 5) {
                        obj['restoreScroll'] = true;
                    } else {
                        obj['scrollScreen'] = true;
                    }
                    buttons.push(obj);
                }
                html += '</div>';
                G("label_recommends").innerHTML = html;
            }


            Epg.autoMakeBtnDir(buttons);
            Epg.btn.init([Epg.getParam('f'), defaultfocus], buttons, '', false);
            Epg.scroll.init({wrapperId: 'ips'});
            G("ips").addEventListener("scroll", throttle(realFunc, 250, 500));
            realFunc();

            Epg.scrollScreen.init({wrapperId: 'home_wrapper', safePx: 5});
            //  Epg.scrollScreen.check(Epg.btn.current);
            realFunc1();
        }, "json")

    },
    initLabelRecommendFail: function () {								// 初始化标签推荐位信息失败处理方法
        var id = Epg.btn.current.id;
        var side = parseInt((SecondPage.sidePrevButtonId).slice(5));
        if ("recommend_down" === id) {
            SecondPage.sidePrevButtonId = "side_" + (side - 1);
        } else {
            SecondPage.sidePrevButtonId = "side_" + (side + 1);
        }
        // 触发侧边栏菜单项获得焦点事件
        Epg.btn.get(SecondPage.sidePrevButtonId).focusHandler({
            id: SecondPage.sidePrevButtonId,
            index: parseInt((SecondPage.sidePrevButtonId).slice(5))
        });
        SecondPage.init();
    },
    navClick: function () {												// 菜单栏点击事件
        SecondPage.updateCurrentUri();
        var code = Epg.btn.current.code;
        if (code === CONFIG.COLUMN_CODE) return;
        if ("ggly_iptv_home" === code) {
            location.href = CONFIG.EPG_PATH + 'column/iptv_home/iptv_home' + CONFIG.EXT + '?f=nav_0';
        } else if ("ggly_iptv_more" === code) {
            location.href = CONFIG.EPG_PATH + 'column/morePage/morePage' + CONFIG.EXT;
        } else if ("ggly_iptv_area" === code) {
            location.href = CONFIG.EPG_PATH + 'column/areaPage/areaPage' + CONFIG.EXT;
        } else if ("nav_order" === code) {
            Epg.go('column/order/order' + CONFIG.EXT);
        } else if ("nav_search" === code) {
            Epg.go('column/search/search' + CONFIG.EXT);
        } else if ("nav_history" === code) {
            Epg.go('column/history/history' + CONFIG.EXT + '?isPlay=true');
        } else if ("nav_fav" === code) {
            Epg.go('column/fav/seriesFav' + CONFIG.EXT + '?isPlay=true');
        } else {
            location.href = CONFIG.EPG_PATH + 'column/secondPage/secondPage' + CONFIG.EXT + '?code=' + code;
        }
    },
    navBeforeMove: function (dir, current) {								// 菜单栏移动前的判断事件
        if ("down" === dir) {
            SecondPage.navPrevButtonId = current.id;
            if (SecondPage.recommendPrevButtonId !== "") {
                Epg.btn.set(SecondPage.recommendPrevButtonId);
            } else if (Epg.btn.get("label_recommend_0")) {
                Epg.btn.set("label_recommend_0");
            } else {
                Epg.btn.set("recommend_big");
            }
            return false;
        }
    },
    recommendUpOrDownFocusHandler: function () {							// 推荐位上下翻页箭头获得焦点事件
        var id = Epg.btn.current.id;
        var side = parseInt((SecondPage.sidePrevButtonId).slice(5));
        if ("recommend_down" === id) {
            SecondPage.sidePrevButtonId = "side_" + (side + 1);
        } else {
            SecondPage.sidePrevButtonId = "side_" + (side - 1);
        }
        // 触发侧边栏菜单项获得焦点事件
        Epg.btn.get(SecondPage.sidePrevButtonId).focusHandler({
            id: SecondPage.sidePrevButtonId,
            index: parseInt((SecondPage.sidePrevButtonId).slice(5))
        });
        SecondPage.init();
    },
    initButtons: function () {											// 初始化光标按钮事件
        buttons = [
            {
                id: 'nav_order',
                code: 'nav_order',
                left: ['nav_7'],
                action: SecondPage.navClick,
                beforeMove: SecondPage.navBeforeMove,
                focusClass: 'nav_order',
                autoDirGroup: 1
            },
            {
                id: 'nav_search',
                code: 'nav_search',
                action: SecondPage.navClick,
                beforeMove: SecondPage.navBeforeMove,
                focusClass: 'nav_search',
                autoDirGroup: 1
            },
            {
                id: 'nav_history',
                code: 'nav_history',
                action: SecondPage.navClick,
                beforeMove: SecondPage.navBeforeMove,
                focusClass: 'nav_history',
                autoDirGroup: 1
            },
            {
                id: 'nav_fav',
                code: 'nav_fav',
                action: SecondPage.navClick,
                beforeMove: SecondPage.navBeforeMove,
                focusClass: 'nav_fav',
                autoDirGroup: 1
            },
            {
                id: 'recommend_big',
                action: SecondPage.recommendClick,
                beforeMove: SecondPage.recommendBeforeMove,
                focusClass: 'recommend_big',
                autoDirGroup: 4
            },
            {id: 'recommend_up', focusHandler: SecondPage.recommendUpOrDownFocusHandler, autoDirGroup: false},
            {id: 'recommend_down', focusHandler: SecondPage.recommendUpOrDownFocusHandler, autoDirGroup: false}
        ];
        for (var i = 0, length = navs.length; i < length; i++) {
            buttons.push({
                id: 'nav_' + i,
                code: navs[i],
                right: i === 7 ? ['nav_order'] : '',
                action: SecondPage.navClick,
                beforeMove: SecondPage.navBeforeMove,
                focusClass: 'nav',
                autoDirGroup: 2
            });
        }
        buttons.push({
            id: 'side_0',
            index: 0,
            action: SecondPage.sideClick,
            beforeMove: SecondPage.sideBeforeMove,
            focusHandler: SecondPage.sideFocusHandler,
            focusClass: 'side',
            autoDirGroup: 3
        });
        for (var i = 0, length = groups[1].metadatas.length; i < length; i++) {
            buttons.push({
                id: 'side_' + (i + 1),
                index: (i + 1),
                value: groups[1].metadatas[i].value,
                action: SecondPage.sideClick,
                beforeMove: SecondPage.sideBeforeMove,
                focusHandler: SecondPage.sideFocusHandler,
                focusClass: 'side',
                autoDirGroup: 3
            });
        }
    },

    updateCurrentUri: function () {
        CONFIG.CURRENT_URI = uri + '&side_idx=' + SecondPage.side_idx + '&sidePrevButtonId=' + SecondPage.sidePrevButtonId + '&navPrevButtonId=' + SecondPage.navPrevButtonId +
            '&recommendPrevButtonId=' + SecondPage.recommendPrevButtonId + '&carousel_index=' + SecondPage.carousel_index;
    }
};
var isEnableButton = false;						// 标识按钮是否生效,用于视频初始化时防止按钮点击生效

CONFIG.COLUMN_CODE = "ggly_iptv_home";
var uri = "column/iptv_home/iptv_home" + CONFIG.EXT + "?1=1";

var animator, ipAnimator;
var recommend_big = [], recommend_big_interval;			// 保存最大推荐位的数据实属无赖,recommend_big_interval--清理定时器
var Home = {
   // userid: Epg.cookie.get("userid"),
    //role: Epg.cookie.get("role"),
   // orderType: Epg.cookie.get("orderType"),
    carousel_index: Epg.getParamInt("carousel_index", 1),	// 大推荐位轮屏到第几个屏
    idx: 0,												// 为了推荐位滚屏到最后一屏不全时,保存最后一位推荐位排序
    navPrevButtonId: Epg.getParam('navPrevButtonId', ''),
    recommendPrevButtonId: Epg.getParam('recommendPrevButtonId', ''),
    ipPrevButtonId: Epg.getParam('ipPrevButtonId', ''),
    recommendScrollLeft: Epg.getParamInt("recommendScrollLeft", 0),	// recommend推荐位列表scrollLeft值
 //   spriteType: Epg.cookie.get('spriteType', ''),
  //  dress: Epg.cookie.get('dress', ''),

    create_recommend_small: function (obj, idx) {	// 两个小推荐位放在一起的推荐位
        var html = '<div>';
        html += '<div class="recommend_small_0">';
        html += '<div id="recommend_' + idx + '"></div>';
        html += '<span class="recommend_span" style="height: 228px;" data-url="' + CONFIG.EPG_PATH + obj[0].linkImageUri + '" data-epg-btn></span>';
        html += '<div id="recommend_' + idx + '_txt" class="recommend_txt">' + obj[0].label + '</div>';
        html += '</div>';
        html += '<div class="recommend_small_1">';
        html += '<div id="recommend_' + (idx + 1) + '"></div>';
        html += '<span class="recommend_span" style="height: 172px;" data-url="' + CONFIG.EPG_PATH + obj[1].linkImageUri + '" data-epg-btn></span>';
        html += '<div id="recommend_' + (idx + 1) + '_txt" class="recommend_txt">' + obj[1].label + '</div>';
        html += '</div>';
        html += '</div>';
        return html;
    },
    create_recommend_middle: function (obj, idx) {	// 一个推荐位放在一起的推荐位
        var html = '<div>';
        html += '<div id="recommend_' + idx + '"></div>';
        html += '<span class="recommend_span" data-url="' + CONFIG.EPG_PATH + obj[0].linkImageUri + '" data-epg-btn></span>';
        html += '<div id="recommend_' + idx + '_txt" class="recommend_txt">' + obj[0].label + '</div>';
        html += '</div>';
        return html;
    },
    autoPlay: function () {							// 最大推荐位进行轮播
        Home.carousel_index++;
        Home.carousel_index = Home.carousel_index >= recommend_big[0].length ? 0 : Home.carousel_index;
        var recom_big = document.querySelectorAll('.recommend_big');
        Array.prototype.slice.call(recom_big).forEach(function (value, index) {
            var span = value.getElementsByTagName('span');
            var li = value.getElementsByTagName('li');
            Array.prototype.slice.call(span).forEach(function (value, index) {
                value.className = index === Home.carousel_index ? 'recommend_big_show' : '';
            });
            Array.prototype.slice.call(li).forEach(function (value, index) {
                value.className = index === Home.carousel_index ? 'recommend_dian' : '';
            });
            value.querySelector('.recommend_txt').innerHTML = recommend_big[index][Home.carousel_index].label;
        });
    },
    create_recommend_big: function (obj, idx) {		// 三个大的推荐位放在一起的推荐位
        var html = '<div class="recommend_big" style="width: 439px;">';
        html += '<div id="recommend_' + idx + '"></div>';
        for (var i = 0, length = recommend_big[0].length; i < length; i++) {
            html += '<span data-url="' + CONFIG.EPG_PATH + obj[i].linkImageUri + '" data-epg-btn class=' + (i === Home.carousel_index ? "recommend_big_show" : "") + '></span>';
        }
        html += '<div id="recommend_' + idx + '_txt" class="recommend_txt" style="width: 433px;">' + obj[Home.carousel_index].label + '</div>';
        html += '<ul>';
        for (i = 0; i < length; i++) {
            html += '<li class=' + (i === Home.carousel_index ? "recommend_dian" : "") + '></li>';
        }
        html += '</ul>';
        html += '</div>';
        return html;
    },
    init2: function () {								// 初始化推荐位方法

        var metadatas = groups[1].metadatas;
        var html = '<div class="recommends"><div class="recommend_first">';
        html += '<div id="recommend_video_txt" class="recommend_video_txt"> </div>';

        html += '<span class="recommend_span_first_0" style="width: 156px; height: 160px; background-image:url(' + CONFIG.EPG_PATH + metadatas[2].linkImageUri + ')"></span>';
        html += '<span class="recommend_span_first_1" style="width: 156px; height: 160px; background-image:url(' + CONFIG.EPG_PATH + metadatas[3].linkImageUri + ')"></span>';

        html += '<div id="recommend_first_0"></div>';
        html += '<div id="recommend_first_1"></div>';
        html += '<div id="recommend_video"></div>';

        html += '</div>';
        var idx = 0, recommend_index = 0;
        buttons.push({
            id: 'recommend_first_0',
            type: metadatas[2].type,
            code: metadatas[2].value,
            up: [],
            down: ['recommend_video'],
            right: 'recommend_first_1',
            action: Home.recommendClick,
            focusHandler: Home.recommendFocusHandler,
            blurHandler: Home.recommendBlurHandler,
            beforeMove: Home.recommendBeforeMoveHandler,
            focusClass: 'recommend_first_0',
            autoDirGroup: 1
        });
        buttons.push({
            id: 'recommend_first_1',
            type: metadatas[3].type,
            code: metadatas[3].value,
            up: [],
            down: ['recommend_video'],
            left: 'recommend_first_0',
            action: Home.recommendClick,
            focusHandler: Home.recommendFocusHandler,
            blurHandler: Home.recommendBlurHandler,
            beforeMove: Home.recommendBeforeMoveHandler,
            focusClass: 'recommend_first_1',
            autoDirGroup: 1
        });

        buttons.push({
            id: 'recommend_video',
            type: metadatas[1].type,
            code: metadatas[1].value,
            up: ['recommend_first_0'],
            down: [],
            action: Home.recommendClick,
            focusHandler: Home.recommendFocusHandler,
            blurHandler: Home.recommendBlurHandler,
            beforeMove: Home.recommendBeforeMoveHandler,
            focusClass: 'recommend_video',
            autoDirGroup: 1
        });
        var obj = {};
        for (var num = 2, i = 0, length = groups.length; num < length; num++, i++) {
            metadatas = groups[num].metadatas;
            if (metadatas.length === 1) {									// 假如是一个中的推荐位
                obj = {
                    id: 'recommend_' + idx,
                    type: metadatas[0].type,
                    code: metadatas[0].value,
                    left: 'recommend_first_1',
                    up: [],
                    down: [],
                    action: Home.recommendClick,
                    focusHandler: Home.recommendFocusHandler,
                    blurHandler: Home.recommendBlurHandler,
                    beforeMove: Home.recommendBeforeMoveHandler,
                    focusClass: 'recommend_middle',
                    autoDirGroup: 1
                };
                buttons.push(obj);
                html += this.create_recommend_middle(metadatas, idx);		// 创建中等推荐位DIV样式
                idx += 1;
            } else if (metadatas.length === 2) {								// 假如是两个小的推荐位堆在一起
                obj = {
                    id: 'recommend_' + idx,
                    type: metadatas[0].type,
                    code: metadatas[0].value,
                    up: [],
                    action: Home.recommendClick,
                    focusHandler: Home.recommendFocusHandler,
                    blurHandler: Home.recommendBlurHandler,
                    beforeMove: Home.recommendBeforeMoveHandler,
                    focusClass: 'recommend_small_0',
                    autoDirGroup: 1
                };
                buttons.push(obj);
                obj = {
                    id: 'recommend_' + (idx + 1),
                    type: metadatas[1].type,
                    code: metadatas[1].value,
                    left: ['recommend_' + (idx - 1), 'recommend_video'],
                    right: ['recommend_' + (idx + 2)],
                    down: [],
                    action: Home.recommendClick,
                    focusHandler: Home.recommendFocusHandler,
                    blurHandler: Home.recommendBlurHandler,
                    beforeMove: Home.recommendBeforeMoveHandler,
                    focusClass: 'recommend_small_1',
                    autoDirGroup: 1
                };
                buttons.push(obj);
                html += this.create_recommend_small(metadatas, idx);		// 创建小等推荐位DIV样式
                idx += 2;
            } else /*if(metadatas.length === 3) */{								// 假如是三个大的推荐位堆在一起
                recommend_big.push(metadatas);
                obj = {
                    id: 'recommend_' + idx,
                    index: recommend_index,
                    tag: 'big',
                    up: [],
                    down: [],
                    action: Home.recommendClick,
                    focusHandler: Home.recommendFocusHandler,
                    blurHandler: Home.recommendBlurHandler,
                    beforeMove: Home.recommendBeforeMoveHandler,
                    focusClass: 'recommend_big',
                    autoDirGroup: 1
                };
                buttons.push(obj);
                html += this.create_recommend_big(metadatas, idx);			// 创建大等推荐位DIV样式
                idx += 1;
                recommend_index += 1;
            }
        }
        Home.idx = idx;
        html += '</div>';
        G("recommends").innerHTML = html;
        G("recommends").scrollLeft = Home.recommendScrollLeft;				// 初始化推荐位的scrollLeft值
    },
    recommendFocusHandler: function () {								// 推荐位获得焦点
        //if(isEnableButton == false)return;
        if ('recommend_first_0' != Epg.btn.current.id && 'recommend_first_1' != Epg.btn.current.id) {
            Epg.marquee.start();
        }
        var position = G(Epg.btn.current.id).getBoundingClientRect();
        var wrapperPosition = G("recommends").getBoundingClientRect();
        var safePx = 50;
        if (position.right >= (wrapperPosition.right - 5)) {			// 如果推荐位右边被隐藏,则推荐位列表向右滚
            if (G("recommend_" + (Home.idx - 1)).getBoundingClientRect().left < 2200) {
                Home.recommendScrollLeft += G("recommend_" + (Home.idx - 1)).getBoundingClientRect().right + safePx - 1280;
            } else {
                Home.recommendScrollLeft += (wrapperPosition.left - position.left + safePx) * -1;
            }
            Epg.addClass(G("home_wrapper"), "home_wrapper");					// 背景替换,把挖空部分补全
            G("recommends").scrollLeft = Home.recommendScrollLeft;
            //Epg.Mp.pause();											// 停止播放
            // TODO 没有办法，只能对视频进行销毁
            Epg.Mp.destroy();
            H('recommend_video_txt');
        } else if (position.left - wrapperPosition.left < 5) {		// 如果推荐位左边被隐藏,则推荐位列表向左滚
            Home.recommendScrollLeft += position.right + safePx - wrapperPosition.right;
            if (Home.recommendScrollLeft < safePx) {
                Home.recommendScrollLeft = 0;
                Epg.removeClass(G("home_wrapper"), "home_wrapper");			// 显示背景挖空部分
                // Epg.Mp.resume();									// 恢复播放
                // TODO 只能进行视频初始化了
                isEnableButton = false;									// 防止视频初始化，按钮点击生效
                Play.playFromProgram(groups[1].metadatas[1].value);		// 播放小视频内容
                S('recommend_video_txt');
            }
            G("recommends").scrollLeft = Home.recommendScrollLeft;
        }
    },
    recommendBlurHandler: function () {								// 推荐位失去焦点
        if ('recommend_first_1' != Epg.btn.previous.id && 'recommend_first_0' != Epg.btn.previous.id) {
            Epg.marquee.stop();
        }
    },
    recommendBeforeMoveHandler: function (dir, current) {			// 推荐位移动前判断事件
        if (!isEnableButton && typeof mp != 'undefined') return false;
        if ("down" === dir && !(current.down && current.down.length > 0)) {
            Home.recommendPrevButtonId = current.id;
            console.log("英藏");
            Epg.btn.set(Home.ipPrevButtonId || "tj_type_state_1");
//Hide('top_tuijian_id');
            return false;
        } else if ("up" === dir && !(current.up && current.up.length > 0)) {
            Home.recommendPrevButtonId = current.id;
            console.log("显示");
            //Show('top_tuijian_id');
            Epg.btn.set(Home.navPrevButtonId || "myorder_div_id");
            return false;
        }
    },
    recommendClick: function () {									// 推荐位点击事件
        if (!isEnableButton && typeof mp != 'undefined') return;									// 初始化视频时,按钮点击事件失效
        Home.updateCurrentUri();
        var id = Epg.btn.current.id, tag = Epg.btn.current.tag;
        if ('big' === tag) {											// 专门对大推荐位进行处理
            var index = Epg.btn.current.index;
            Home.isOrder({
                type: recommend_big[index][Home.carousel_index].type,
                code: recommend_big[index][Home.carousel_index].value
            });
        } else if ('recommend_video' === id) {
            if ("free" != Home.orderType) {
                Epg.goMP('column/mp/mp' + CONFIG.EXT + '?method=playFromProgram&pid=' + Play.programId + '&code=' + Play.videoCode);
            } else {
                Epg.go('column/order/order' + CONFIG.EXT + '?source=' + CONFIG.COLUMN_CODE + '&code=' + Play.videoCode);
            }
        } else {
            Home.isOrder({type: Epg.btn.current.type, code: Epg.btn.current.code});
        }
    },
    isOrder: function (recommend) {									// 推荐位等的判断事件
        var type = recommend.type, code = recommend.code;
        if ('album' === type || 'activity' === type || 'column' === type) {
            Home.getActivityOrAlbum(code);
        } else if ('recommend_series' === type) {
            Epg.go('column/subSeries/subSeries' + CONFIG.EXT + '?code=' + code);
        } else {
            if ("free" != Home.orderType) {
                Epg.goMP('column/mp/mp' + CONFIG.EXT + '?method=playVideo&code=' + code);
            } else {
                Epg.go('column/order/order' + CONFIG.EXT + '?source=' + CONFIG.COLUMN_CODE + '&code=' + code);
            }
        }
    },
    getActivityOrAlbum: function (code) {							// 进入活动或者专辑页面
        var postData = {'code': code, 'appVersion': CONFIG.APP_VERSION, 'role': Home.role};
        Epg.postAPI('epg/get', postData, function (data) {
            if (data && data.code === 0) {
                Epg.go(data.epg.path);
            }
        });
    },
    ipFocusHandler: function () {					// IP形象获得焦点
        var id = Epg.btn.current.id;
        //G(id).style.right = "50px";				// 防止IP形象错位

    },
    ipBlurHandler: function () {						//	IP形象失去焦点
        var id = Epg.btn.previous.id;
        //G(id).style.right= "50px";				// 恢复IP形象原始位置

    },
    ipBeforeMoveHandler: function (dir, current) {	// IP形象移动前的判断事件
        if (!isEnableButton && typeof mp != 'undefined') return false;
        if ("down" === dir && !(current.down && current.down.length > 0)) {
            Home.ipPrevButtonId = current.id;
            console.log("ipBeforeMoveHandler英藏");
            Epg.btn.set(SecondPage.recommendPrevButtonId||"label_recommend_0");

            return false;
        } else if ("up" === dir && !(current.up && current.up.length > 0)) {
            Home.ipPrevButtonId = current.id;
            console.log("ipBeforeMoveHandler显示");
            Epg.btn.set(Home.recommendPrevButtonId || "nav_0");
            return false;
        }
    },
    ipClick: function () {

        console.log("IP点击事件");// IP点击事件
        if (!isEnableButton && typeof mp != 'undefined') return;					// 初始化视频时,按钮点击事件失效
        var domid= Epg.btn.current.id;
        type_id=domid.slice(-1);
        defaultfocus=domid;
        SecondPage.recommendPrevButtonId="label_recommend_0";
        SecondPage.initLabelRecommend(type_id);
    },
    sortClick: function () {

        console.log("sortClick点击事件");// IP点击事件
        var domid= Epg.btn.current.id;
       var id=domid.slice(-1);
        console.log("sortClick点击事件"+id);// IP点击事件
        sort=id;
        defaultfocus=domid;
        SecondPage.initLabelRecommend(type_id);
    },
    navBeforeMoveHandler: function (dir, current) {	// 导航条移动前的判断事件
        if ("down" === dir) {
            Home.navPrevButtonId = current.id;
            Epg.btn.set(Home.recommendPrevButtonId || "tj_type_id_1");
            return false;
        }

    },
    jump_order:function(){
     window.location.href="order.html?userId="+userId;


    },
    navClick: function () {							// 导航条点击事件
        if (!isEnableButton && typeof mp != 'undefined') return;					// 初始化视频时,按钮点击事件失效
        var code = Epg.btn.current.code;
        if (code === CONFIG.COLUMN_CODE) return;
        Home.updateCurrentUri();
        if ('ggly_iptv_area' === code) {
            location.href = CONFIG.EPG_PATH + 'column/areaPage/areaPage' + CONFIG.EXT + '?source=' + CONFIG.COLUMN_CODE;
        } else if ('ggly_iptv_more' === code) {
            location.href = CONFIG.EPG_PATH + 'column/morePage/morePage' + CONFIG.EXT + '?source=' + CONFIG.COLUMN_CODE;
        } else if ("nav_order" === code) {
            if ("month" == Home.orderType) {
                Epg.tip('您是已订购用户，无需重复订购');
            } else {
                Epg.go('column/order/order' + CONFIG.EXT);
            }
        } else if ("nav_search" === code) {
            Epg.go('column/search/search' + CONFIG.EXT);
        } else if ("nav_history" === code) {
            Epg.go('history' + CONFIG.EXT + '?isPlay=true');
        } else if ("nav_fav" === code) {
            Epg.go('column/fav/seriesFav' + CONFIG.EXT + '?isPlay=true');
        } else {
            location.href = CONFIG.EPG_PATH + 'column/secondPage/secondPage' + CONFIG.EXT + '?code=' + code + '&source=' + CONFIG.COLUMN_CODE;
        }
    },
    updateCurrentUri: function () {
        CONFIG.CURRENT_URI = uri + '&navPrevButtonId=' + Home.navPrevButtonId + '&recommendPrevButtonId=' + Home.recommendPrevButtonId + '&ipPrevButtonId=' + Home.ipPrevButtonId +
            '&recommendScrollLeft=' + Home.recommendScrollLeft + '&carousel_index=' + Home.carousel_index;
    },
    initAnimator: function () {						// 初始化左下角动画形象
        var len = {
            'bear_dress_0': 20, 'bear_dress_1': 31, 'bear_dress_2': 31, 'bear_dress_3': 34,
            'rabbit_dress_0': 26, 'rabbit_dress_1': 31, 'rabbit_dress_2': 31, 'rabbit_dress_3': 36
        };
        if ('' === Home.dress || '' === Home.spriteType) {
            S('animators');
            G("animators").style.backgroundImage = 'url(images/ip_first.gif)';
        } else {
            H('animators');
            Home.ipLen = len[Home.dress];
            var html = '<div class="animators">';
            for (var i = 1; i <= Home.ipLen; i++) {
                html += '<div data-url="images/animator/' + Home.spriteType + '/' + Home.dress + '/' + (i < 10 ? ('0' + i) : i) + '.png" data-epg-btn></div>';
            }
            html += '</div>';
            G("animators").innerHTML = html;
            G("animators").scrollTop = 0;
            G('animators').style.backgroundImage = 'url()';
            G('animator').style.backgroundImage = 'url(images/animator/' + Home.spriteType + '/' + Home.dress + '/' + Home.ipLen + '.png)';

            var index = 0;
            ipAnimator = new Animator(100 * Home.ipLen, function (p) {
                index = Math.floor(p * Home.ipLen);
                if (index >= Home.ipLen) {
                    index = 0;
                }
                G("animators").scrollTop = index * 215;
            });
            ipAnimator.start(function () {
                H('animator');
                S('animators');
                Home.animatorStart();
            });
        }
    },
    animatorStart: function () {						// 动画形象摆动方法
        var index = 0;
        ipAnimator = new Animator(100 * Home.ipLen, function (p) {
            index = Math.floor(p * Home.ipLen);
            if (index >= Home.ipLen) {
                index = 0;
            }
            G("animators").scrollTop = index * 215;
        });
        ipAnimator.start(function () {
            Home.animatorStart();
        });
    },
    ipSelectAction: function () {					// IP形象选择点击事件
        var id = Epg.btn.current.id;
        Home.spriteType = id;						// 当前用户选择的IP形象
        Home.dress = Home.spriteType + '_dress_0';	// 用户拥有的初始装扮
        Home.subject = 'subject_0';					// 用户拥有的初始主题
        Home.scene = 'scene_0';						// 用户拥有的初始精灵背景
        Epg.cookie.set('spriteType', Home.spriteType);
        Epg.cookie.set('dress', Home.dress);
        Epg.cookie.set('subject', Home.subject);
        Epg.cookie.set('scene', Home.scene);
        // 选择IP形象后，赠送100个金币
        Epg.postAPI('gold/updateGoldTotal', {
            'numValue': 100,
            'userId': Home.userid,
            'operation': 'add',
            'source': CONFIG.COLUMN_CODE
        });
        Epg.postAPI('baby/update-parameter', {
            'userId': Home.userid,
            'type': 'all',
            'spriteType': Home.spriteType,
            'dress': Home.dress
        });
        //Epg.postAPI('baby/update-parameter', {'userId':Home.userid, 'type':'spriteType', 'spriteType':Home.spriteType});
        //Epg.postAPI('baby/update-parameter', {'userId':Home.userid, 'type':'dress', 'dress':Home.dress});
        /*Epg.postAPI('baby/update-parameter', {'userId':Home.userid, 'type':'subject', 'subject':Home.subject});
         Epg.postAPI('baby/update-parameter', {'userId':Home.userid, 'type':'scene', 'scene':Home.scene});*/
        Epg.postAPI('consumeLog/add', {'userid': Home.userid, 'type': 'dress', 'value': Home.dress});
        //Epg.postAPI('consumeLog/add', {'userid':Home.userid, 'type':'subject', 'value':Home.subject});
        //Epg.postAPI('consumeLog/add', {'userid':Home.userid, 'type':'scene', 'value':Home.scene});
        H('popup');									// 隐藏弹窗
        Home.initAnimator();						// 重新设置动画形象
        Epg.btn.set('ip_first');
        // Epg.Mp.resume();							// 恢复播放
        isEnableButton = false;									// 防止视频初始化，按钮点击生效
        Play.playFromProgram(groups[1].metadatas[1].value);		// 播放小视频内容
    }
};

var buttons = [

    {
        id: 'myorder_div_id',
        code: 'myorder_div_id',
        action: Home.jump_order,
        beforeMove: Home.navBeforeMoveHandler,
        focusClass: 'tj',
        autoDirGroup: 1
    },


];
//var ipslength = window.document.getElementsByClassName("tj_type_1");
//console.log("ipslength:::" + ipslength.length);
//for (var i = 0; i < ipslength.length; i++) {
//    var obj = {
//        id: 'tj_type_id_' + (i + 1),
//        action: Home.ipClick,
//        focusHandler: Home.ipFocusHandler,
//        blurHandler: Home.ipBlurHandler,
//        beforeMove: Home.recommendBeforeMoveHandler,
//        up: [],
//        down: [],
//        focusClass: 'tj',
//        autoDirGroup: 4,
//        scrollDir: 'x'
//    };
//    if (i === 0) {
//        obj['left'] = ['ip_first'];
//        obj['restoreScroll'] = true;
//    } else {
//        obj['scrollScreen'] = true;
//    }
//    buttons.push(obj);
//}
var obj1 = {
    id: 'tj_type_state_1',
    action: Home.sortClick,
    focusHandler: Home.ipFocusHandler,
    blurHandler: Home.ipBlurHandler,
    beforeMove: Home.ipBeforeMoveHandler,
    up: [],
    down: "",
    focusClass: 'tj',
    autoDirGroup: 5
};
var obj2 = {
    id: 'tj_type_state_2',
    action: Home.sortClick,
    focusHandler: Home.ipFocusHandler,
    blurHandler: Home.ipBlurHandler,
    beforeMove: Home.ipBeforeMoveHandler,
    up: [],
    down: "",
    focusClass: 'tj',
    autoDirGroup: 5
};
var obj3 = {
    id: 'tj_type_state_3',
    action: Home.sortClick,
    focusHandler: Home.ipFocusHandler,
    blurHandler: Home.ipBlurHandler,
    beforeMove: Home.ipBeforeMoveHandler,
    up: [],
    down: "",
    focusClass: 'tj',
    autoDirGroup: 5
};
buttons.push(obj1);
buttons.push(obj2);
buttons.push(obj3);
function back() {


    window.history.go(-1);

}

// 简单的节流函数
function throttle(func, wait, mustRun) {
    var timeout, startTime = new Date();
    return function () {
        var context = this, args = arguments, curTime = new Date();
        clearTimeout(timeout);
        // 如果达到了规定的触发时间间隔，触发 handler
        if (curTime - startTime >= mustRun) {
            //func.apply(context,args);
            func();
            startTime = curTime;
            // 没达到触发间隔，重新设定定时器
        } else {
            timeout = setTimeout(func, wait);
        }
    };
};
// 实际想绑定在 scroll 事件上的 handler
function realFunc(wrapperId) {
    wrapperId = wrapperId || Epg.scroll.config.wrapperId;
    var iScrollLeft = G(wrapperId).scrollLeft;
    var iClientLeft = G(wrapperId).getBoundingClientRect().left + iScrollLeft;
    var iClientRight = G(wrapperId).offsetWidth + iClientLeft;
    var btns = G(wrapperId).querySelectorAll("[data-epg-btn]");
    for (var i = 0; i < btns.length; i++) {
        var obj = btns[i];
        // 加载过了的就不需要加载了
        if (!Epg.hasClass(obj, "loaded")) {
            var iLeft = Epg.getAbsolutePosition(obj).left;
            var iRight = iLeft + obj.offsetWidth;
            if ((iLeft > iClientLeft && iLeft < iClientRight) || (iRight > iClientLeft && iRight < iClientRight)) {
                obj.style.backgroundImage = 'url(' + obj.getAttribute("data-url") + ')';
                Epg.addClass(obj, "loaded");
            }
        }
    }
}
// 实际想绑定在 scroll 事件上的 handler
function realFunc1(wrapperId) {
    wrapperId = wrapperId || Epg.scrollScreen.config.wrapperId;
    var iScrollTop = G(wrapperId).scrollTop;
    var iClientTop = G(wrapperId).getBoundingClientRect().top + iScrollTop;
    var iClientBottom = G(wrapperId).offsetHeight + iClientTop;
    var btns = document.querySelectorAll("[data-epg-btn]");
    for (var i = 0; i < btns.length; i++) {
        var obj = btns[i];
        // 加载过了的就不需要加载了
        if (!Epg.hasClass(obj, "loaded")) {
            var iTop = Epg.getAbsolutePosition(obj).top;
            var iBottom = iTop + obj.offsetHeight;
            if ((iTop > iClientTop && iTop < iClientBottom) || (iBottom > iClientTop && iBottom < iClientBottom)) {
                obj.style.backgroundImage = 'url(' + obj.getAttribute("data-url") + ')';
                Epg.addClass(obj, "loaded");
            }
        }
    }
}

// 实际想绑定在 scrollTop 事件上的 handler
function realFuncTop(wrapperId) {
    var iScrollTop = G(wrapperId).scrollTop;
    var iClientTop = G(wrapperId).getBoundingClientRect().top + iScrollTop;
    var iClientBottom = G(wrapperId).offsetHeight + iClientTop;

    var iClientTop0 = iClientTop - 2 * G(wrapperId).offsetHeight;
    var iClientBottom0 = iClientBottom - 2 * G(wrapperId).offsetHeight;

    var iClientTop2 = iClientTop + 2 * G(wrapperId).offsetHeight;
    var iClientBottom2 = iClientBottom + 2 * G(wrapperId).offsetHeight;

    var btns = G(wrapperId).querySelectorAll("[data-epg-btn]");
    console.log("btns:" + btns.length);
    for (var i = 0; i < btns.length; i++) {
        var obj = btns[i];
        // 加载过了的就不需要加载了
        if (!Epg.hasClass(obj, "loaded")) {
            var iTop = Epg.getAbsolutePosition(obj).top;
            var iBottom = iTop + obj.offsetHeight;
            if ((iTop >= iClientTop && iTop <= iClientBottom) || (iBottom >= iClientTop && iBottom <= iClientBottom)) {
                obj.style.backgroundImage = 'url(' + obj.getAttribute("data-url") + ')';
                Epg.addClass(obj, "loaded");
            } else if ((iTop >= iClientTop0 && iTop <= iClientBottom0) || (iBottom >= iClientTop0 && iBottom <= iClientBottom0)) {
                obj.style.backgroundImage = 'url(' + obj.getAttribute("data-url") + ')';
                Epg.addClass(obj, "loaded");
            } else if ((iTop >= iClientTop2 && iTop <= iClientBottom2) || (iBottom >= iClientTop2 && iBottom <= iClientBottom2)) {
                obj.style.backgroundImage = 'url(' + obj.getAttribute("data-url") + ')';
                Epg.addClass(obj, "loaded");
            }
        }
    }
}
function init() {

    Epg.autoMakeBtnDir(buttons);
    Epg.btn.init([Epg.getParam('f'), 'myorder_div_id'], buttons, '', false);


    Epg.scroll.init({wrapperId: 'ips'});
    realFunc();
    G("ips").addEventListener("scroll", throttle(realFunc, 250, 500));


}
function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = decodeURI(window.location.search).substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return 1;
}
var type_id= getQueryString('id');
var sort=1;//1-智能排序；2-人气（点击量）排序；3-销量排序；
var defaultfocus='tj_type_id_'+type_id;
console.log("type_id:::"+type_id);
var userId=localStorage.getItem("UserID");

$(function(){



    window.method = "playFromProgram";
    Epg.key.init();
    Epg.key.set({
        KEY_BACK: 'back()',
        KEY_5:'back()',
        KEY_ENTER: 'Epg.Button.click()',			//确定键
        KEY_LEFT: 'Epg.Button.move("left")',		//左键
        KEY_RIGHT: 'Epg.Button.move("right")',		//右键
        KEY_UP: 'Epg.Button.move("up")',			//上键
        KEY_DOWN: 'Epg.Button.move("down")',		//下键

    });
    Epg.key.set({
        KEY_VOL_UP: 'Epg.Mp.volUp()',
        KEY_VOL_DOWN: 'Epg.Mp.volDown()'
    });
    if (Home.recommendScrollLeft > 0) {				// 如果推荐位发生了滚动,补全空白处
        Epg.addClass(G("home_wrapper"), "home_wrapper");
    }

    show_loading();

    SecondPage.initRecommend(type_id);

    window.onload = function(){
        stop_loading();

    }

    // 初始化
    G("home_wrapper").addEventListener('scroll', throttle(realFunc1, 250, 500));

})
